package com.nhjf.mobile.controller.admin.teacher;
import net.sf.json.JSONObject;
import com.nhjf.command.system.CreateTeacherCommand;
import com.nhjf.common.page.Pagination;
import com.nhjf.common.util.MD5;
import com.nhjf.mobile.common.util.SysProperties;
import com.nhjf.model.system.AdminSession;
import com.nhjf.model.system.Role;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.OperationLog;
import com.nhjf.model.teachers.Teacher;
import com.nhjf.pojo.qo.system.AdminSessionQo;
import com.nhjf.pojo.qo.system.UserQo;
import com.nhjf.pojo.qo.teachers.OrganizationHasStudentQo;
import com.nhjf.pojo.qo.teachers.TeachersQo;
import com.nhjf.service.system.AdminSessionService;
import com.nhjf.service.system.UserService;
import com.nhjf.service.teachers.OperationLogService;
import com.nhjf.service.teachers.TeachersService;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Controller
@RequestMapping(value = "/teach")
public class TeachersAdminController {

	@Autowired
	private TeachersService teachersService;
	@Autowired
	private OperationLogService  operationLogService;
	@Autowired
	private UserService userSerivce;
	@Autowired
	private AdminSessionService adminSessionService;
	@Autowired
	private UserService userService;
	/**
	 * 查询老师列表
	 * @param response
	 * @param request
	 * @param teachersQo
	 * @param stuQo
	 * @param model
	 * @param page
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/teachlist")
	public String Coursescc(String phone,String name,HttpServletResponse response,HttpServletRequest request, @RequestParam(value="page", defaultValue="1")Integer page,@RequestParam(value="token", required=true) String token){
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员不能操作!");
						return JSONObject.fromObject(resMap).toString();
					}
					if(user.getIsRole()==3) {
						TeachersQo teachersQo = new TeachersQo();
						teachersQo.setSeachUser(true);
						if(StringUtils.isNotEmpty(phone)){
							teachersQo.setPhoneNumber(phone);
						}
						if(StringUtils.isNotEmpty(name)){
							teachersQo.setNickname(name);
						}
						TeachersQo tqo=new TeachersQo();
						tqo.setUserId(user.getId());
						tqo.setSeachOrganization(true);
						Teacher teacher=teachersService.queryUnique(tqo);
						if(teacher.getTraininginstitution()!=null && teacher.getTraininginstitution().getId()!=null) {
							teachersQo.setOrganizationId(teacher.getTraininginstitution().getId());
						}else {
							// 跳转到登录页面
							response.sendRedirect(request.getContextPath()+"/login");
						}
						//			stuQo.setOrganization();
						Pagination pagination = new Pagination();
						pagination.setPageSize(20);
						pagination.setCondition(teachersQo);
						pagination.setPageNo(page);
						pagination = teachersService.queryPagination(pagination);
						List<Teacher> tList=(List<Teacher>) pagination.getList();
						for (Teacher teacher2 : tList) {
							teacher2.getUser().setUserPassword("");
						}
						pagination.setList(tList);
						resMap.put("code", "200");
						resMap.put("message", pagination);
						return JSONObject.fromObject(resMap).toString();
					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}


		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "异常抛出!");
			return JSONObject.fromObject(resMap).toString();
		}
		return "";
	}
	/**
	 * 查看老师详情
	 * @param response
	 * @param request
	 * @param teachersQo
	 * @param model
	 * @param id
	 * @param token
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/teacherView")
	public String Views(HttpServletResponse response,HttpServletRequest request,String id,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {

			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员无法操作!");
						return JSONObject.fromObject(resMap).toString();
					}
					SysProperties sysProperties=SysProperties.getInstance();
					//			 String filePath=sysProperties.get("imagePath")+"teacher/"+name+"."+extension;
					String imagePath=sysProperties.get("imagePath");
					Set<Role> set= user.getRoleList();
					Teacher teacher= teachersService.get(Long.parseLong(id));
					if(teacher!=null) {
						if(!StringUtils.isEmpty(teacher.getAvatar())) {
							if(teacher.getAvatar().indexOf(imagePath+"/picture/")>=0) {

							}else {
								teacher.setAvatar(imagePath+"/picture/"+teacher.getAvatar());
							}
						}
						resMap.put("code", "200");
						resMap.put("message",teacher);
						return JSONObject.fromObject(resMap).toString();
					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			resMap.put("code", "500");
			resMap.put("message", "异常抛出!");
			return JSONObject.fromObject(resMap).toString();
		}
		resMap.put("code", "500");
		resMap.put("message", "操作异常!");
		return JSONObject.fromObject(resMap).toString();
	}
	/**
	 * 根据id删除老师
	 * @param response
	 * @param request
	 * @param teachersQo
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/teacherDel")
	public String teacDel(HttpServletResponse response,HttpServletRequest request,String id,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员无法操作!");
						return JSONObject.fromObject(resMap).toString();
					}
					TeachersQo qo=new TeachersQo();
					qo.setSeachUser(true);
					qo.setTeacherId(Long.parseLong(id));
					Teacher teacher=teachersService.queryUnique(qo);  //找到id进行修改
					Long id1= teacher.getUser().getId();
					User user1=new User();
					user1=userSerivce.get(id1);
					user1.setItsusableornot(2);
					User users= userSerivce.update(user1);
					if(users!=null) {
						OperationLog operationLog=new OperationLog();
						operationLog.setOperationType(1);
						operationLog.setOperationDescription("删除老师!");
						operationLog.setUserId(user);
						operationLog.setOperationTime(new Date());
						operationLog.setOperationUserName(user.getUserName());
						operationLogService.save(operationLog);
						resMap.put("code", "200");
						resMap.put("message", "删除成功!");
						return JSONObject.fromObject(resMap).toString();
					}

				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}
			/*Teacher teacher=teachersService.get(Long.parseLong(id));  //找到id进行修改
			teacher.getUser().setItsusableornot(2);
			Teacher ts= teachersService.update(teacher);*/

		} catch (Exception e) {
			// TODO: handle exception
			resMap.put("code", "500");
			resMap.put("message", "异常抛出!");
			return JSONObject.fromObject(resMap).toString();
		}
		resMap.put("code", "500");
		resMap.put("message", "操作异常!");
		return JSONObject.fromObject(resMap).toString();
	}


	/**
	 * 重置密码
	 * @param response
	 * @param request
	 * @param teachersQo
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/teacherCzMima")
	public String teacCzMima(HttpServletResponse response,HttpServletRequest request,Model model,String id,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员无法操作!");
						return JSONObject.fromObject(resMap).toString();
					}
					TeachersQo teachersQo=new TeachersQo();
					teachersQo.setSeachUser(true);
					teachersQo.setTeacherId(Long.parseLong(id));
					teachersQo.setSeachOrganization(true);
					Teacher tc=teachersService.queryUnique(teachersQo);
					model.addAttribute("names",tc.getName());
					UserQo qo=new UserQo();
					qo.setUserId(tc.getUser().getId());
					qo.setSeachRole(true);
					User user1=userSerivce.queryUnique(qo);
					user1.setUserPassword(MD5.MD5Encode("123456"));
					User users= userSerivce.update(user1);
					if(users!=null) {
						OperationLog operationLog=new OperationLog();
						operationLog.setOperationType(3);
						operationLog.setOperationDescription("重置老师密码!");
						operationLog.setUserId(user);
						operationLog.setOperationTime(new Date());
						operationLog.setOperationUserName(user.getUserName());
						operationLogService.save(operationLog);
						resMap.put("code", "200");
						resMap.put("message", "密码重置成功!");
						return JSONObject.fromObject(resMap).toString();
					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "异常抛出!");
			return JSONObject.fromObject(resMap).toString();
		}
		resMap.put("code", "500");
		resMap.put("message", "操作异常!");
		return JSONObject.fromObject(resMap).toString();
	}
	@RequestMapping("/teachertzadd")
	public String teachertzAdd() {

		return "/teacher/teacher_add.html";
	}
	/**
	 * 验证老师是否存在
	 * @param command
	 * @param token
	 * @return
	 */
	@RequestMapping("/verifyAccount")
	@ResponseBody
	public String verifyAccount(CreateTeacherCommand command,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员无法操作!");
						return JSONObject.fromObject(resMap).toString();
					}
					UserQo qo=new UserQo();
					if(StringUtils.isNotBlank(command.getAccountNumber())) {
						qo.setUserName(command.getAccountNumber());
						User user1= userSerivce.queryUnique(qo);
						if(user1!=null) {
							resMap.put("code", "500");
							resMap.put("message", "此账号已经存在!");
							return JSONObject.fromObject(resMap).toString();
						}else {
							resMap.put("code", "200");
							resMap.put("message", "通过!");
							return JSONObject.fromObject(resMap).toString();
						}
					}else {
						resMap.put("code", "500");
						resMap.put("message", "失败!");
						return JSONObject.fromObject(resMap).toString();
					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "异常抛出!");
			return JSONObject.fromObject(resMap).toString();
		}
		resMap.put("code", "500");
		resMap.put("message", "操作异常!");
		return JSONObject.fromObject(resMap).toString();



	}
	/**
	 * 添加老师账号
	 * @param response
	 * @param request
	 * @param model
	 * @param teacher
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/teacherAdd",method=RequestMethod.POST)
	public String teacAdd(HttpServletResponse response,HttpServletRequest request,Model model,@ModelAttribute CreateTeacherCommand teacher,
			/*MultipartFile imgFile,*/@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo1=new UserQo();
				userQo1.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo1);
				if(user!=null) {
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员无法操作!");
						return JSONObject.fromObject(resMap).toString();
					}
					if(teacher.getNickname()==null) {
						resMap.put("code", "500");
						resMap.put("message", "请填写昵称!");
						return JSONObject.fromObject(resMap).toString();
					}
					if(teacher.getPhoneNumber()==null) {
						resMap.put("code", "500");
						resMap.put("message", "请填写手机号!");
						return JSONObject.fromObject(resMap).toString();
					}
					if(teacher.getPassword()==null) {
						resMap.put("code", "500");
						resMap.put("message", "请填写登陆密码!");
						return JSONObject.fromObject(resMap).toString();
					}
					if(teacher.getAccountNumber()==null) {
						resMap.put("code", "500");
						resMap.put("message", "请填用户账号!");
						return JSONObject.fromObject(resMap).toString();
					}
					//					if(teacher.getRemarks()==null) {
					//						resMap.put("code", "500");
					//						resMap.put("message", "请填用户账号!");
					//						return JSONObject.fromObject(resMap).toString();
					//					}
					//判断文件是否为空
//					if (imgFile.isEmpty()) {
//						resMap.put("code", "500");
//						resMap.put("message", "请选择图片!");
//						return JSONObject.fromObject(resMap).toString();
//					}
//					int returnTag = -1;
					// 获取图片原始文件名
//					String originalFilename = imgFile.getOriginalFilename();
//					System.out.println(originalFilename);

					//              文件名使用当前时间
//					String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
					//              获取上传图片的扩展名(jpg/png/...)
//					String extension = FilenameUtils.getExtension(originalFilename);
//					String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
//					boolean flag = false;
//					// 判断文件格式是否合法
//					for (String str : regular) {
//						if (extension.equalsIgnoreCase(str)) {
//							flag = true;
//						}
//					}
//					if (!flag) {
//						returnTag = 0;
//						resMap.put("code", "500");
//						resMap.put("message", "图片格式不对!");
//						return JSONObject.fromObject(resMap).toString();
//					}
					//图片上传的绝对路径
//					SysProperties sysProperties=SysProperties.getInstance();
//					String filePath=sysProperties.get("profilepicture")+name+"."+extension;
//					//				 String filePahts=sysProperties.get("imagePath");
//					//				 model.addAttribute("filePahts",filePahts);         获取路径
//					String imgPath="picture/"+name+"."+extension;
//					File dir = new File(filePath);
//					if (!dir.exists()) {
//						dir.mkdirs();
//					}
					// 上传图片
//					imgFile.transferTo(new File(filePath));
					TeachersQo teachersQo=new TeachersQo();
					Teacher teacherss=new Teacher();
					UserQo userQo=new UserQo();
					User users=new User();
					userQo.setUserName(teacher.getPhoneNumber());
					users=userSerivce.queryUnique(userQo);
					if(users==null) {
						teachersQo.setPhoneNumber(teacher.getPhoneNumber()); 
						teacherss=teachersService.queryUnique(teachersQo);
						if(teacherss==null) {//判断此账号是否已存在
							TeachersQo teachersQo1=new TeachersQo();
							teachersQo1.setUserId(user.getId());
							teachersQo1.setSeachOrganization(true);
							Teacher teachers=teachersService.queryUnique(teachersQo1);
							Long id= teachers.getTraininginstitution().getId();
							teacher.setTraininginstitutionid(id);
//							teacher.setAvatar(imgPath);
							teacher.setPassword(MD5.MD5Encode(teacher.getPassword()));
							teachersService.createTeacher(teacher);
							OperationLog operationLog=new OperationLog();
							operationLog.setOperationType(2);
							operationLog.setOperationDescription("新增老师!");
							operationLog.setUserId(user);
							operationLog.setOperationTime(new Date());
							operationLog.setOperationUserName(user.getUserName());
							operationLogService.save(operationLog);
							resMap.put("code", "200");
							resMap.put("message", "新增成功!");
							return JSONObject.fromObject(resMap).toString();
						}else {
							resMap.put("code", "500");
							resMap.put("message", "老师账号已经存在!");
							return JSONObject.fromObject(resMap).toString();
						}
					}else {
						resMap.put("code", "500");
						resMap.put("message", "用户已经存在!");
						return JSONObject.fromObject(resMap).toString();
					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}


		}  catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "异常抛出!");
			return JSONObject.fromObject(resMap).toString();
		}
		resMap.put("code", "500");
		resMap.put("message", "操作异常!");
		return JSONObject.fromObject(resMap).toString();
	}

}
